<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\VipOrderModel;
use App\Services\Logger;
use App\Services\PayServices;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;

class VipOrderDao extends BaseDao
{


    public static function get_vip_order_builder($params = []){
        $query = VipOrderModel::query();

        $query->when(checkIsHasField($params,'vip_order_id'),function ($query)use ($params){
            $query->where('vip_order_id',$params['vip_order_id']);
        });


        $query->when(checkIsHasField($params,'order_code'),function ($query)use ($params){
            $query->where('order_code',$params['order_code']);
        });

        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });


        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        return $query;
    }

    /**
     * @throws InvalidArgumentException
     * @throws SysExceptions
     * @throws GuzzleException
     * @throws InvalidConfigException
     */
    public static function add_vip_order($params = []): array
    {

        $VipInfo = VipSettingsDao::get_vip_info([
            'vip_id'=>$params['vip_id']
        ]);
        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$params['user_id']
        ])->first();
        if($userInfo['vip_index'] >= $VipInfo['vip_index']){
            self::error('已经是合伙人');
        }
        $params['order_code'] = makeOrderNo();
        $params['vip_order_price'] = $VipInfo['vip_price'];
        $params['vip_json_info'] = json_encode($VipInfo,JSON_UNESCAPED_UNICODE);
        //安放节点等



        //计算都给谁返钱

        if(self::get_vip_order_builder()->create($params) === false){
            self::error('订单创建失败');
        }


        return PayServices::pay([
            'notify_url'=>route('notice_vip'),
            'order_code'=>$params['order_code'],
            'price'=>$params['vip_order_price'],
            'openid'=>UsersDao::get_user_builder([
                'user_id'=>$params['user_id']
            ])->value('openid')
        ]);
    }

    /**
     * @throws SysExceptions
     */
    public static function changeVip($order_code = '')
    {

        Logger::info("+======>微信",[
            'order_code'=>$order_code
        ]);
        $orderInfo = VipOrderDao::get_vip_order_builder([
            'order_code'=>$order_code,
            'status'=>0
        ]);
        if(!$orderInfo->exists()){
            Logger::info('++++.微信订单不存在');
            self::error('订单不存在');
        }
        $orderInfo = $orderInfo->first()->toArray();
        $vipJsonInfo = json_decode($orderInfo['vip_json_info'],true);
        DB::beginTransaction();
        //修改用户vip等级
        $res  = VipOrderDao::get_vip_order_builder([
            'order_code'=>$order_code,
            'status'=>0
        ])->update([
            'status'=>1
        ]);
        $res !== false && $res = UsersDao::get_user_builder([
            'user_id'=>$orderInfo['user_id']
        ])->update([
            'vip_index'=>$vipJsonInfo['vip_index']
        ]);
        if($res === false){
            DB::rollBack();
            self::error('失败');
        }
        DB::commit();
        self::changeVipAutoPointUid($orderInfo['user_id']);
    }


    /**
     * @throws SysExceptions
     */
    public static function changeVipAutoPointUid($user_id)
    {
        Logger::data("====》自动",[
            $user_id
        ]);
        $userInfo = UsersDao::get_user_builder([
            'user_id'=>$user_id
        ]);
        if(!$userInfo->exists()){
            self::error('用户不存在');
        }
        $userInfo = $userInfo->first()->toArray();
        $userUpperInfo = UsersDao::get_user_builder([
            'user_id'=>$userInfo['spread_id']
        ])->first();
        //判断上级是否开了自动
        if($userUpperInfo['is_auto'] ==0){
            return false;
        }
        //获取点位下级
        $poinFList = UsersDao::get_user_builder([
            'point_uid'=>$userUpperInfo['user_id']
        ])->get()->toArray();
        //第一层没满=>就是自己名下
        if(count($poinFList) < 3){
            UsersDao::set_point_uid([
                'user_id'=>$userInfo['spread_id'],//上级用户
                'b_uid'=>$userInfo['user_id'],
                'point_uid'=>$userInfo['spread_id'],
                'point_uid_index'=>(count($poinFList)+1)
            ]);
        }else{
            //够三个了,放到自己的第一、二市场
            //一个用户id
            $vUserId = $poinFList[2]['user_id'];
            $users = [$vUserId];
            while (true){
                $res = false;
                foreach ($users as $value){
                    $vvList = UsersDao::get_user_builder([
                        'point_uid'=>$value
                    ])->get();
                    Logger::data('+++++++++++>',$vvList->toArray());
                    if(count($vvList) < 2){

                        UsersDao::set_point_uid([
                            'user_id'=>$userInfo['spread_id'],//上级用户
                            'b_uid'=>$userInfo['user_id'],
                            'point_uid'=>$value,
                            'point_uid_index'=>count($vvList)+1
                        ]);
                        $res = true;
                        break;
                    }
                }
                if($res){
                    break;
                }
                $users = array_column($vvList->toArray(),'user_id');
            }
        }

    }


}
